package su2010.puz.extractors;

import su2010.puz.Extractor;
import su2010.puz.ImageHelper;
import su2010.puz.impl.Histogram;
import su2010.puz.util.ImageCls;

/**
 * Extractor for the RGBL maxima count 
 * ne svida mi se previse al posto ce sve slike koristiti isto mislim da ce bit ok :D
 * @author stef
 *
 */
public class HistogramMaxima implements Extractor {

	private Histogram histogram;
	private int numOutput = 1;
	private int color_mode;
	
	public HistogramMaxima() {
		color_mode = ImageHelper.LUMINANCE;
	}
	
	private int[] smooth(int[] hist, int winSize){
		int[] smoothed = new int[hist.length];
		int windowSize = winSize/2;
		float sum = 0;
		for(int i = windowSize; i<hist.length-windowSize; i++){
			sum = 0;
			for(int j = i-windowSize; j <= i+windowSize; j++)
				sum+=hist[j];
			smoothed[i] =(int)(sum/(float)winSize);
		}
		for(int i = 0;i<windowSize;i++){
			sum = 0;
			int count = 0;
			for(int j = 0;j<windowSize-i;j++){
				sum+=hist[j];
				count ++;
			}
			smoothed[i] = (int)(sum/(float)count);
		}
		for(int i = hist.length-windowSize;i<hist.length;i++){
			sum = 0;
			int count = 0;
			for(int j = i-windowSize;j<hist.length;j++){
				sum+=hist[j];
				count ++;
			}
			smoothed[i] = (int)(sum/(float)count);
		}
		return smoothed;
	}
	
	public void smooth(int i){
		if (histogram == null) throw new RuntimeException("Invalid call! Call setImage() method first!");
		int[] smoothed = smooth(histogram.getHistogram(ImageHelper.RED),i);
		histogram.showHistogram(smoothed, ImageHelper.RED, Integer.toString(i));
	}
	
	private int countMaxima(int color){
		int[] hist = histogram.getHistogram(color);
		hist = smooth(hist,7);
		//histogram.showHistogram(hist, ImageHelper.RED, Integer.toString(color));
		float deltax;
		float x = hist[0];
		int count =0;
		boolean up = false;
		int interval = 5;
		for(int i = 0; i< hist.length; i+=interval){
			deltax = 0;
			for(int j = i; j < i+interval && j < hist.length; j++){
				deltax+=hist[j];
			}
			deltax /= 10f;
			if(i == 0){
				if(x-deltax > 0)
					up = true;
				else
					up = false;
			}
			else{
				if(up && x-deltax < 0){
					count ++;
					up = false;
				}
				if(!up && x-deltax > 0)
					up = true;
			}
			x = deltax;
		}
		return count;
	}

	@Override
	public int getNumOutput() {
		return numOutput;
	}

	@Override
	public void setImage(ImageCls image) {
		histogram = image.getHistogram();
	}

	public void setColor_mode(int color_mode) {
		this.color_mode = color_mode;
	}
	
	@Override
	public float[] extract() {
		float val = countMaxima(color_mode)/20.f;
		return new float[]{val};
	}

	@Override
	public String getName() {
		return ImageHelper.getColorName(color_mode)+" Histogram Maxima"; 
	}
}
